import { SysMenu } from '../api/menu';

/**
 * 路由生成器工具类
 * 用于根据菜单配置动态生成前端路由和页面文件
 */
export class RouteGenerator {
  /**
   * 根据菜单路径生成页面组件模板
   * @param menu 菜单对象
   * @returns 页面组件代码
   */
  static generatePageComponent(menu: SysMenu): string {
    const componentName = this.getComponentName(menu.menuPath || '');
    const pageName = menu.menuName;
    
    return `import React, { useState, useEffect } from 'react';
import {
  Card,
  Typography,
  Space,
  Button,
  Table,
  Modal,
  Form,
  Input,
  Toast,
  Spin,
} from '@douyinfe/semi-ui';
import { IconPlus, IconEdit, IconDelete, IconRefresh } from '@douyinfe/semi-icons';

const { Title } = Typography;

interface ${componentName}Data {
  id?: number;
  name: string;
  description?: string;
  status: number;
  createTime?: string;
  updateTime?: string;
}

const ${componentName}: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [dataList, setDataList] = useState<${componentName}Data[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingItem, setEditingItem] = useState<${componentName}Data | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      // TODO: 实现数据加载逻辑
      // const response = await api.getData();
      // setDataList(response);
      console.log('加载${pageName}数据');
    } catch (error) {
      console.error('加载数据失败:', error);
      Toast.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingItem(null);
    form.reset();
    setModalVisible(true);
  };

  const handleEdit = (item: ${componentName}Data) => {
    setEditingItem(item);
    form.setValues(item);
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      // TODO: 实现删除逻辑
      // await api.deleteItem(id);
      Toast.success('删除成功');
      loadData();
    } catch (error) {
      console.error('删除失败:', error);
      Toast.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingItem) {
        // TODO: 实现更新逻辑
        // await api.updateItem(editingItem.id!, values);
        Toast.success('更新成功');
      } else {
        // TODO: 实现创建逻辑
        // await api.createItem(values);
        Toast.success('创建成功');
      }
      setModalVisible(false);
      loadData();
    } catch (error) {
      console.error('保存失败:', error);
      Toast.error('保存失败');
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status: number) => (
        status === 1 ? '启用' : '禁用'
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      width: 200,
      render: (record: ${componentName}Data) => (
        <Space>
          <Button
            theme="borderless"
            type="primary"
            size="small"
            icon={<IconEdit />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            theme="borderless"
            type="danger"
            size="small"
            icon={<IconDelete />}
            onClick={() => handleDelete(record.id!)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <Card>
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Title heading={4}>${pageName}管理</Title>
          <Button
            theme="solid"
            type="primary"
            icon={<IconPlus />}
            onClick={handleAdd}
          >
            新增
          </Button>
          <Button
            icon={<IconRefresh />}
            onClick={loadData}
          >
            刷新
          </Button>
        </Space>
      </div>

      <Spin spinning={loading}>
        <Table
          columns={columns}
          dataSource={dataList}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
          rowKey="id"
        />
      </Spin>

      <Modal
        title={editingItem ? '编辑${pageName}' : '新增${pageName}'}
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          onSubmit={handleSubmit}
          labelPosition="left"
          labelWidth={100}
        >
          <Form.Input
            field="name"
            label="名称"
            placeholder="请输入名称"
            rules={[{ required: true, message: '请输入名称' }]}
          />
          <Form.TextArea
            field="description"
            label="描述"
            placeholder="请输入描述"
            rows={3}
          />
          <Form.Select
            field="status"
            label="状态"
            placeholder="请选择状态"
            rules={[{ required: true, message: '请选择状态' }]}
            optionList={[
              { label: '启用', value: 1 },
              { label: '禁用', value: 0 },
            ]}
          />
        </Form>
      </Modal>
    </Card>
  );
};

export default ${componentName};
`;
  }

  /**
   * 根据路径生成组件名称
   * @param path 路径
   * @returns 组件名称
   */
  static getComponentName(path: string): string {
    if (!path) return 'DefaultPage';
    
    // 移除开头的斜杠并分割路径
    const segments = path.replace(/^\//, '').split('/');
    
    // 将每个段落转换为首字母大写的驼峰命名
    const componentName = segments
      .map(segment => segment.charAt(0).toUpperCase() + segment.slice(1))
      .join('');
    
    return componentName || 'DefaultPage';
  }

  /**
   * 根据路径生成文件路径
   * @param menuPath 菜单路径
   * @returns 文件路径
   */
  static getFilePath(menuPath: string): string {
    if (!menuPath) return 'src/pages/DefaultPage.tsx';
    
    // 移除开头的斜杠
    const cleanPath = menuPath.replace(/^\//, '');
    
    // 如果路径包含多个段落，创建嵌套目录
    const segments = cleanPath.split('/');
    if (segments.length > 1) {
      const dirPath = segments.slice(0, -1).join('/');
      const fileName = this.getComponentName(segments[segments.length - 1]);
      return `src/pages/${dirPath}/${fileName}.tsx`;
    } else {
      const fileName = this.getComponentName(cleanPath);
      return `src/pages/${fileName}.tsx`;
    }
  }

  /**
   * 生成路由配置
   * @param menus 菜单列表
   * @returns 路由配置代码
   */
  static generateRouteConfig(menus: SysMenu[]): string {
    const imports: string[] = [];
    const routes: string[] = [];

    menus.forEach(menu => {
      if (menu.menuPath && menu.menuType === 2) { // 菜单类型为页面
        const componentName = this.getComponentName(menu.menuPath);
        const importPath = this.getFilePath(menu.menuPath).replace('src/', '../').replace('.tsx', '');
        
        imports.push(`import ${componentName} from '${importPath}';`);
        routes.push(`  {
    path: '${menu.menuPath}',
    element: <${componentName} />,
    meta: {
      title: '${menu.menuName}',
      requiresAuth: true,
    },
  },`);
      }
    });

    return `import React from 'react';
${imports.join('\n')}

export const dynamicRoutes = [
${routes.join('\n')}
];
`;
  }

  /**
   * 生成API接口模板
   * @param menu 菜单对象
   * @returns API接口代码
   */
  static generateApiTemplate(menu: SysMenu): string {
    const entityName = this.getComponentName(menu.menuPath || '').replace('Management', '').replace('Page', '');
    const apiName = entityName.toLowerCase();
    
    return `import request, { PageQuery, PageResponse } from './request';

export interface ${entityName} {
  id?: number;
  name: string;
  description?: string;
  status: number;
  createTime?: string;
  updateTime?: string;
}

export interface ${entityName}Query extends PageQuery {
  name?: string;
  status?: number;
}

export const ${apiName}Api = {
  // 分页查询
  page: (params: ${entityName}Query) => 
    request.get<PageResponse<${entityName}>>('/api/${apiName}/page', { params }),

  // 获取详情
  getById: (id: number) => 
    request.get<${entityName}>(\`/api/${apiName}/\${id}\`),

  // 创建
  create: (data: Omit<${entityName}, 'id' | 'createTime' | 'updateTime'>) => 
    request.post<${entityName}>('/api/${apiName}', data),

  // 更新
  update: (id: number, data: Partial<${entityName}>) => 
    request.put<${entityName}>(\`/api/${apiName}/\${id}\`, data),

  // 删除
  delete: (id: number) => 
    request.delete(\`/api/${apiName}/\${id}\`),

  // 批量删除
  batchDelete: (ids: number[]) => 
    request.delete('/api/${apiName}/batch', { data: { ids } }),
};
`;
  }

  /**
   * 生成完整的页面文件结构说明
   * @param menu 菜单对象
   * @returns 文件结构说明
   */
  static generateFileStructureGuide(menu: SysMenu): string {
    const componentName = this.getComponentName(menu.menuPath || '');
    const filePath = this.getFilePath(menu.menuPath || '');
    const apiFileName = `${componentName.toLowerCase().replace('management', '').replace('page', '')}.ts`;
    
    return `
# ${menu.menuName} 页面文件生成指南

## 需要创建的文件：

### 1. 页面组件文件
**路径**: \`${filePath}\`
**说明**: 主要的页面组件，包含CRUD操作界面

### 2. API接口文件
**路径**: \`src/api/${apiFileName}\`
**说明**: 后端API接口定义和调用方法

### 3. 路由配置
**文件**: \`src/router/index.tsx\`
**说明**: 需要在路由配置中添加新的路由项

## 开发步骤：

1. 创建页面组件文件
2. 创建对应的API接口文件
3. 在路由配置中添加路由
4. 根据实际业务需求调整页面组件
5. 实现后端API接口
6. 测试页面功能

## 注意事项：

- 确保路由路径与菜单配置中的路径一致
- API接口需要与后端开发人员协调
- 页面权限控制需要与权限系统集成
- 组件样式需要与整体UI风格保持一致
`;
  }
}

export default RouteGenerator;